<template>
	<div class="table">
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item><i class="el-icon-tickets"></i> 机构</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container,parent">
			<div class="tree-left">
				<el-tree :data="dataTree" node-key="index" :default-checked-keys="[1]" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
			</div>
			<div class="div-right">
				<div class="handle-box">
					<el-button type="primary" icon="add" class="handle-add mr10" @click="add()">添加</el-button>
					<el-input v-model="select_word" placeholder="根据名称模糊搜索" class="handle-input mr10"></el-input>
					<el-button type="primary" icon="search" @click="search">搜索</el-button>
				</div>
				<el-table :data="data" border style="width: 100%" ref="tableData" @selection-change="handleSelectionChange">
					<!--<el-table-column type="selection" width="55"></el-table-column>-->
					<el-input type="hidden" prop="id" sortable />
					<el-table-column prop="name" label="班次名称">
					</el-table-column>
					<el-table-column label="操作" width="280">
						<template slot-scope="scope">
							<!-- <el-button size="small" @click="handleUser(scope.$index, scope.row)">查看用户</el-button> -->
							<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
							<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="pagination">
					<el-pagination @current-change="handleCurrentChange" layout="prev, pager, next" :total="total">
					</el-pagination>
				</div>
			</div>
		</div>

		<el-dialog title="添加" :visible.sync="addVisible" width="60%">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="班次名称:" prop="name" label-width="90px">
					<el-input v-model="form.name" style="width:150px;"></el-input>
					<div>最多10个字符或数字</div>
				</el-form-item>
				<el-form-item label="设置该班次一天内上下班的次数:" label-width="220px">
					<el-radio-group v-model="form.type" size="small">
						<el-radio-button label="1" @click.native="open(1)">1天1次上下班</el-radio-button>
						<el-radio-button label="2" @click.native="open(2)">1天2次上下班</el-radio-button>
						<el-radio-button label="3" @click.native="open(3)">1天3次上下班</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<div v-for="(itemDe,index) in form.detailItem" :key="index" style="margin-left: 8px;margin-top: 20px;">
					<div style="margin-left: -30px">
						<el-row>
							<el-col :span="8" class="myvalidate">
								<el-form-item class="item " label-width="0px" :prop="'detailItem.'+index+'.startTime'" :rules="[{ required: true, message: '上班时间不能为空', trigger: 'blur' }]">
									<span style="padding-left:30px;">第{{index+1}}次 上班</span>
									<el-time-picker v-model="itemDe.startTime" :picker-options="{
                              selectableRange: '00:00:00 - 23:59:59'
                            }"
									 format="HH:mm" placeholder="上班时间">
									</el-time-picker>
								</el-form-item>
							</el-col>
							<el-col :span="9">
								<el-form-item class="item" label-width="0px" :prop="'detailItem.'+index+'.endTime'" :rules="{ required: true, message: '下班时间不能为空', trigger: 'blur' }">
									<span style="padding-left:30px;">下班:</span>
									<el-time-picker v-model="itemDe.endTime" :picker-options="{
                              selectableRange: '00:00:00 - 23:59:59'
                            }"
									 format="HH:mm" placeholder="下班时间">
									</el-time-picker>
								</el-form-item>
							</el-col>
						</el-row>

					</div>
					<div style="margin-top: 20px">
						<el-row>
							<el-col :span="9">
								<el-form-item class="item" label-width="0px">
									<el-checkbox label="休息时间" v-model="itemDe.restCheck"></el-checkbox>
									<span style="padding-left:30px;">开始:</span>
									<el-time-picker v-model="itemDe.restStartTime" :picker-options="{
                                selectableRange: '00:00:00 - 23:59:59'
                              }"
									 format="HH:mm" placeholder="休息开始">
									</el-time-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="item" label-width="0px">
									<span style="padding-left:30px;">结束:</span>
									<el-time-picker v-model="itemDe.restEndTime" :picker-options="{
                            selectableRange: '00:00:00 - 23:59:59'
                          }"
									 format="HH:mm" placeholder="休息结束">
									</el-time-picker>
								</el-form-item>
							</el-col>
						</el-row>


					</div>
				</div>
				<div class="">
					工作总时长:{{form.duration}}
				</div>
				<div class="errmsg">
					{{errmsg}}
				</div>

			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addVisible = false">取 消</el-button>
				<el-button type="primary" @click="addDetail">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog title="编辑" :visible.sync="editVisible" width="60%">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="班次名称:" prop="name" label-width="90px">
					<el-input v-model="form.name" style="width:150px;"></el-input>
					<div>最多10个字符或数字</div>
				</el-form-item>
				<el-form-item label="设置该班次一天内上下班的次数:" label-width="220px">
					<el-radio-group v-model="form.type" size="small">
						<el-radio-button label="1" @click.native="open(1)">1天1次上下班</el-radio-button>
						<el-radio-button label="2" @click.native="open(2)">1天2次上下班</el-radio-button>
						<el-radio-button label="3" @click.native="open(3)">1天3次上下班</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<div v-for="(itemDe,index) in form.detailItem" :key="index" style="margin-left: 8px;margin-top: 20px;">
					<div style="margin-left: -30px">
						<el-row>
							<el-col :span="8" class="myvalidate">
								<el-form-item class="item " label-width="0px" :prop="'detailItem.'+index+'.startTime'" :rules="[{ required: true, message: '上班时间不能为空', trigger: 'blur' }]">
									<span style="padding-left:30px;">第{{index+1}}次 上班</span>
									<el-time-picker v-model="itemDe.startTime" :picker-options="{
                              selectableRange: '00:00:00 - 23:59:59'
                            }"
									 format="HH:mm" placeholder="上班时间">
									</el-time-picker>
								</el-form-item>
							</el-col>
							<el-col :span="9">
								<el-form-item class="item" label-width="0px" :prop="'detailItem.'+index+'.endTime'" :rules="{ required: true, message: '下班时间不能为空', trigger: 'blur' }">
									<span style="padding-left:30px;">下班:</span>
									<el-time-picker v-model="itemDe.endTime" :picker-options="{
                              selectableRange: '00:00:00 - 23:59:59'
                            }"
									 format="HH:mm" placeholder="下班时间">
									</el-time-picker>
								</el-form-item>
							</el-col>
						</el-row>

					</div>
					<div style="margin-top: 20px">
						<el-row>
							<el-col :span="9">
								<el-form-item class="item" label-width="0px">
									<el-checkbox label="休息时间" v-model="itemDe.restCheck"></el-checkbox>
									<span style="padding-left:30px;">开始:</span>
									<el-time-picker v-model="itemDe.restStartTime" :picker-options="{
                                selectableRange: '00:00:00 - 23:59:59'
                              }"
									 format="HH:mm" placeholder="休息开始">
									</el-time-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="item" label-width="0px">
									<span style="padding-left:30px;">结束:</span>
									<el-time-picker v-model="itemDe.restEndTime" :picker-options="{
                            selectableRange: '00:00:00 - 23:59:59'
                          }"
									 format="HH:mm" placeholder="休息结束">
									</el-time-picker>
								</el-form-item>
							</el-col>
						</el-row>


					</div>
				</div>
				<div class="">
					工作总时长:{{form.duration}}
				</div>
				<div class="errmsg">
					{{errmsg}}
				</div>

			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="updateDetail">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 删除提示框 -->
		<el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
			<div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="delVisible = false">取 消</el-button>
				<el-button type="primary" @click="deleteRow">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data: function() {

			return {
				url: './static/vuetable.json',
				tableData: [],
				cur_page: 1,
				total: 1,
				multipleSelection: [],
				select_cate: '',
				select_word: '',
				del_list: [],
				is_search: false,
				addVisible: false,
				editVisible: false,
				delVisible: false,
				form: {
					mechanismId: '',
					name: '',
					type: '1',
					content: '',
					startTime: '',
					endTime: '',
					id: '',
					detailItem: [{
						startTime: '',
						endTime: '',
						restStartTime: '',
						restEndTime: '',
						restCheck: false,
					}],
					duration: '',
				},
				errmsg: '',
				rules: {
					name: [{
						required: true,
						message: '请填写班次名称',
						trigger: 'blur'
					}],
				},
				detailCount: 1,
				idx: -1,
				dataTree: [],
				defaultProps: {
					children: 'list',
					label: 'name'
				}

			}
		},
		created() {
			this.getMechanism();
			this.getData()

		},
		computed: {
			data() {
				return this.tableData.filter((d) => {
					let is_del = false;
					for (let i = 0; i < this.del_list.length; i++) {
						if (d.name === this.del_list[i].name) {
							is_del = true;
							break;
						}
					}
					if (!is_del) {
						return d;
					}
				})
			}
		},
		methods: {
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 分页导航
			handleCurrentChange(val) {
				this.cur_page = val;
				this.getMechanism();
			},
			add() {
				if (this.form.mechanismId == undefined || this.form.mechanismId == '') {
					this.$message.error("请选择机构");
					return;
				}
				this.form.name = '';
				this.addVisible = true;
				this.detailCount = this.form.detailItem.length
				if (this.detailCount >= 1) {
					this.open(1);
				}
				if (this.detailCount == 1) {
					this.form.detailItem.splice(0, 1);
				}
				this.form.detailItem.push({
					startTime: '',
					endTime: '',
					restStartTime: '',
					restEndTime: '',
					restCheck: false,
				})

			},
			open(index) {

				if (index > this.detailCount) {
					for (var i = 0; i < index - this.detailCount; i++) {
						this.form.detailItem.push({
							startTime: '',
							endTime: '',
							restStartTime: '',
							restEndTime: '',
							restCheck: false,
						})
					}
				}
				if (index < this.detailCount) {

					for (var i = 0; i < this.detailCount - index; i++) {
						this.form.detailItem.splice(index, 1);
					}
				}

				this.detailCount = index;
				// this.ruleSelectById();

			},
			checkDateTime() {
				var res = true;
				var baseTime = null;
				var that = this;
				var dateDiff = 0;
				for (var i = 0; i < this.form.detailItem.length; i++) {

					if (baseTime == null) {
						baseTime = this.form.detailItem[i].startTime;

					}

					if (this.form.detailItem[i].startTime < baseTime) {
						that.errmsg = "当前上班时间要小于上次下班时间";
						res = false;
						break;
					}
					/**
					 * 开始时间不能大于结束时间
					 */
					if (this.form.detailItem[i].startTime > this.form.detailItem[i].endTime) {
						that.errmsg = "第" + (i + 1) + "次上班 开始时间不能大约结束时间";
						res = false;
						break;
					}
					dateDiff += this.form.detailItem[i].endTime.getTime() - this.form.detailItem[i].startTime.getTime(); //时间差的毫秒数


					/**
					 * 选择有休息时间
					 */
					if (this.form.detailItem[i].restCheck == true) {
						if (this.form.detailItem[i].restStartTime == undefined || this.form.detailItem[i].restStartTime == '') {
							that.errmsg = "第" + (i + 1) + "次上班 休息开始时间不能为空";
							res = false;
							break;
						}
						if (this.form.detailItem[i].restEndTime == undefined || this.form.detailItem[i].restEndTime == '') {
							that.errmsg = "第" + (i + 1) + "次上班 休息结束时间不能为空";
							res = false;
							break;
						}

						if (this.form.detailItem[i].restStartTime > this.form.detailItem[i].restEndTime) {
							that.errmsg = "第" + (i + 1) + "次上班 休息结束时间必须大于休息开始时间";
							res = false;
							break;
						}
						/**
						 * 休息开始时间必须  在上班 开始 和结束时间之间
						 */
						if (this.form.detailItem[i].restEndTime > this.form.detailItem[i].endTime) {

							that.errmsg = "第" + (i + 1) + "次上班 休息结束时间不能大于下班时间";
							res = false;
							break;
						}

						if (this.form.detailItem[i].restStartTime < this.form.detailItem[i].startTime) {
							that.errmsg = "第" + (i + 1) + "次上班 休息开始时间不能大于上班时间";
							res = false;
							break;
						}
						dateDiff -= this.form.detailItem[i].restEndTime - this.form.detailItem[i].restStartTime

					}
					/**
					 * 结束后把当前下班时间赋值给下次的判断依据
					 */
					baseTime = this.form.detailItem[i].endTime;

				}
				if (dateDiff != 0) {
					var minutes = Math.floor(dateDiff / (60 * 1000)) //计算相差分钟数
					this.form.duration = Math.floor(minutes / 60) + "小时" + Math.floor(minutes % 60) + "分钟";
				}

				return res;
			},
			parseTime() {
				var tempTime = JSON.parse(JSON.stringify(this.form.detailItem));
				for (var i = 0; i < this.form.detailItem.length; i++) {
					if (this.form.detailItem[i].startTime != null) {
						var tmp = this.form.detailItem[i].startTime;
						tempTime[i].startTime = this.buLing(tmp.getHours()) + ":" + this.buLing(tmp.getMinutes())
					}

					if (this.form.detailItem[i].endTime != null) {
						var tmp = this.form.detailItem[i].endTime;
						tempTime[i].endTime = this.buLing(tmp.getHours()) + ":" + this.buLing(tmp.getMinutes())
					}
					if (this.form.detailItem[i].restCheck == true) {
						if (this.form.detailItem[i].restStartTime != null) {
							var tmp = this.form.detailItem[i].restStartTime;
							tempTime[i].restStartTime = this.buLing(tmp.getHours()) + ":" + this.buLing(tmp.getMinutes())
						}
						if (this.form.detailItem[i].restEndTime != null) {
							var tmp = this.form.detailItem[i].restEndTime;
							tempTime[i].restEndTime = this.buLing(tmp.getHours()) + ":" + this.buLing(tmp.getMinutes())
						}
					} else {
						tempTime[i].restStartTime = null;
						tempTime[i].restEndTime = null;
					}

				}
				return JSON.stringify(tempTime);
			},
			buLing(str) {
				if (str.length == 1) {
					str = "0" + str;
				}
				return str
			},
			updateDetail() {
				var that = this;
				this.$refs["form"].validate((valid) => {
					if (valid) {
						if (that.checkDateTime()) {
							that.errmsg = '';
							that.HttpUtil.encryptPut(
								that,
								that.Global.URLPATH.RULE_CLASS_UPDATE, {
									id: that.form.id,
									name: that.form.name,
									detailItem: that.parseTime(),
									duration: that.form.duration
								},
								function(data) {
									that.$message.success("修改成功");
									that.editVisible = false;

								},
								function(data) { //访问失败
									//that.$message.success(data.msg);
								});
						}
					}

				});
			},
			addDetail() {
				var that = this;
				this.$refs["form"].validate((valid) => {
					if (valid) {
						if (that.checkDateTime()) {
							that.errmsg = '';
							that.HttpUtil.encryptPost(
								that,
								that.Global.URLPATH.RULE_CLASS_INSERT, {
									mechanismId: this.form.mechanismId,
									name: that.form.name,
									detailItem: that.parseTime(),
									duration: that.form.duration
								},
								function(data) {
									that.$message.success(data.msg);
									that.addVisible = false;

								},
								function(data) { //访问失败
									//that.$message.success(data.msg);
								});
						}
					}

				});
			},
			ruleSelectById() {

				var that = this;
				console.log(that.form.detailItem);
				that.HttpUtil.encryptGet(
					that,
					that.Global.URLPATH.RULE_CLASS_DETAIL_SELECTBYID, {
						ruleClassId: that.form.id,
					},
					function(data) {
						that.form.detailItem.splice(0, 1);
						if (data.data != null && data.data != undefined && data.data.detailItem != null && data.data.detailItem !=
							undefined) {
							for (var i in data.data.detailItem) {
								var item = data.data.detailItem[i]
								item.restCheck = true
								item.startTime = that.getTime(item.startTime)
								item.endTime = that.getTime(item.endTime)
								item.restStartTime = that.getTime(item.restStartTime)
								item.restEndTime = that.getTime(item.restEndTime)
								that.form.detailItem.push(item)
							}

						}

					},
					function(data) { //访问失败
						//that.$message.success(data.msg);
					});
			},
			queryByName() {
				this.tableData = [];
				this.total = 1;
				var that = this;
				this.HttpUtil.encryptGet(
					this,
					this.Global.URLPATH.RULE_CLASS_QUERY, {
						mechanismId: this.form.mechanismId,
						pageNum: that.cur_page,
						name: this.select_word
					},
					function(data) {
						data = data.data;
						that.total = data.total;
						that.tableData = data.list
					},
					function(data) { //访问失败
						that.tableData = [];
						that.total = 1;
						that.$message.success(data.msg);
					});
			},
			getMechanism() {
				var that = this;

				this.HttpUtil.encryptGet(
					this,
					this.Global.URLPATH.MECHANISM_NOPAGE_QUERY, {
						token: sessionStorage.getItem("token")
					},
					function(data) {
						if (data.data != null && data.data != undefined) {
							for (var i in data.data) {
								if (i == 0) {
									that.form.mechanismId = data.data[i].id;

								}
								data.data[i].index = parseInt(i) + 1;
							}
							that.dataTree = data.data;
							getData(that.form.mechanismId)
						}

					},
					function(data) { //访问失败
						//that.$message.success(data.msg);
					});
			},
			// 获取 easy-mock 的模拟数据
			getData(mechanismId) {				
				this.tableData = [];
				this.total = 0;
				/**
				 * 执行查询
				 */
				var that = this;
				this.HttpUtil.encryptGet(
					this,
					this.Global.URLPATH.RULE_CLASS_QUERY, {
						mechanismId: mechanismId,
						pageNum: that.cur_page
					},
					function(data) {
						data = data.data;
						that.total = data.total;
						that.tableData = data.list

					},
					function(data) { //访问失败
						//that.$message.success(data.msg);
					});
			},
			search() {
				this.is_search = true;
				this.cur_page = 1;
				this.queryByName();

			},

			// 确定删除
			deleteRow() {
				let that = this;
				//发送请求
				this.HttpUtil.encryptDelete(
					this,
					this.Global.URLPATH.RULE_CLASS + this.form.id, {
						id: this.form.id
					},
					function(data) {
						that.delVisible = false;
						that.getData(that.form.mechanismId);
						that.$message.success("删除成功:");
					},
					function(data) {
						that.$message.success("删除失败:" + data.msg);
					});

			},
			//树形控件点击
			handleNodeClick(data) {
				this.form.mechanismId = data.id;
				this.getData(data.id) 				
			},
			handleDelete(index, row) {
				const item = this.tableData[index];
				this.form.name = item.name;
				this.form.id = item.id;
				this.delVisible = true;

			},
			handleEdit(index, row) {
				const item = this.tableData[index];
				this.form.name = item.name;
				this.form.id = item.id;
				this.editVisible = true;
				this.ruleSelectById();
			},
			getTime(str) {

				if (str == null || str == undefined || str.split(":").length != 2) {
					return ""
				}
				var date = new Date();
				date.setHours(str.split(":")[0]);
				date.setMinutes(str.split(":")[1]);
				return date;
			},
		},
		watch: {
			$route(newValue, oldValue) {
				if (newValue.path == "/dept") {
					this.getMechanism();
				}
			}
		}
	}
</script>

<style scoped>
	.handle-box {
		margin-bottom: 10px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		padding-left: 66%;
		display: inline-block;
	}

	.del-dialog-cnt {
		font-size: 16px;
		text-align: center
	}

	.parent {
		padding: 30px;
		background: #fff;
		border: 1px solid #ddd;
		border-radius: 5px;
	}

	.tree-left {
		width: 20%;
		height: 100%;
		float: left;
	}

	.div-right {
		width: 80%;
		height: 100%;
		float: left;

	}

	.detail2 {
		display: none;
	}

	.myvalidate .el-form-item__content .el-form-item__error {
		padding-left: 100px;
	}

	.errmsg {
		color: #f56c6c;
		font-size: 12px;
		line-height: 1;
		padding-top: 4px;
		/* position: absolute; */
		top: 100%;
		left: 0;
	}
</style>
